import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import Student from 'src/entities/student.entity';
import { Repository } from 'typeorm';
import { FindStudentDto, UpdateStudentDto } from './student.dto';
import { isEmpty } from 'lodash';
import { ApiException } from 'src/core/exceptions/api.exception';
import User from 'src/entities/user.entity';
import Resume from 'src/entities/resume.entity';

@Injectable()
export class StudentService {
  constructor(
    @InjectRepository(Student) private studentRepository: Repository<Student>,
    @InjectRepository(User) private userRepository: Repository<User>,
    @InjectRepository(Resume) private resumeRepository: Repository<Resume>,
  ) {}

  // 查询
  async find(query: FindStudentDto) {
    const { page, size, name, studentNumber } = query;

    const queryBuilder = this.studentRepository
      .createQueryBuilder('student')
      .skip(size * (page - 1))
      .take(size)
      .where((qb) => {
        if (name !== undefined) {
          qb.andWhere('student.name Like :name', { name: `%${name}%` });
        }
      });

    const [list, count] = await queryBuilder.getManyAndCount();

    const studentPromise = list.map(async (item) => {
      const queryBuilder = this.userRepository
        .createQueryBuilder('user')
        .select(['user.username', 'user.avatar', 'user.nickname'])
        .where('user.id = :id', { id: item.userId });
      if (studentNumber !== undefined) {
        queryBuilder.andWhere('user.username Like :studentNumber', {
          studentNumber: `%${studentNumber}%`,
        });
      }

      const user = await queryBuilder.getOne();

      if (isEmpty(user)) {
        return {};
      } else {
        return { ...item, user: user };
      }
    });

    const studentList = await Promise.all(studentPromise);

    const arr = studentList.filter((item) => {
      if (Object.keys(item).length === 0) {
        return false;
      }
      return true;
    });

    return { list: arr, count };
  }

  // 获取详细
  async info(id: string): Promise<Student> {
    return await this.studentRepository.findOne({
      where: { userId: id },
      select: ['id', 'name', 'birth', 'sex', 'major', 'college', 'experience', 'skill'],
    });
  }

  // // 获取详细
  // async detail(id: string) {
  //   const student = await this.studentRepository.findOne({
  //     where: { userId: id },
  //     select: ['id', 'name', 'birth', 'sex', 'major', 'college', 'experience', 'skill'],
  //   });
  //   if (isEmpty(student)) {
  //     throw new ApiException(12001);
  //   }
  //   const resume = await this.resumeRepository.findOne({ where: { id: student.id } });
  //   return { ...student, url: resume.url || '' };
  // }

  // 更新
  async update(updateStudentDto: UpdateStudentDto) {
    const student = await this.studentRepository.findOne({ where: { id: updateStudentDto.id } });
    if (isEmpty(student)) {
      throw new ApiException(12001);
    }

    const updateStudent = this.studentRepository.merge(student, updateStudentDto);
    await this.studentRepository.save(updateStudent);
  }
}
